//
//  OrderDetailViewController.m
//  myhuibao
//
//  Created by lijun on 13-4-10.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "OrderDetailViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "OMGToast.h"
#import "SBJson.h"
#import "OrderListViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "RestaurantDetailViewController.h"
@interface OrderDetailViewController ()

@end

@implementation OrderDetailViewController
@synthesize orderNo;
@synthesize otherReq;
@synthesize merchantName;
@synthesize bookTime;
@synthesize boxName;
@synthesize foodTime;
@synthesize num;
@synthesize confMes;
@synthesize orderNoId;
@synthesize orderType;
@synthesize mdview;
@synthesize merchantId;
@synthesize req;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self startRequest];
    mdview.layer.cornerRadius=5;
    mdview.layer.borderWidth=1;
    mdview.layer.borderColor=LINE_COLOR.CGColor;
    [[mdview layer] setShadowOffset:CGSizeMake(1, 1)];
    [[mdview layer] setShadowRadius:1];
    [[mdview layer] setShadowOpacity:1];
    [[mdview layer] setShadowColor:LINE_COLOR.CGColor];
	// Do any additional setup after loading the view.
    _btCancel.hidden=true;
    if(orderType!=1)
    {
        _lbGap.hidden=YES;
        _lbBoxTitle.hidden=YES;
        boxName.hidden=YES;
        [_lbSMSTitle setFrame:CGRectMake(_lbSMSTitle.frame.origin.x, _lbSMSTitle.frame.origin.y-42, _lbSMSTitle.frame.size.width, _lbSMSTitle.frame.size.height)];
        [_tvSMS setFrame:CGRectMake(_tvSMS.frame.origin.x, _tvSMS.frame.origin.y-42, _tvSMS.frame.size.width, _tvSMS.frame.size.height)];
    }
}

- (void)viewDidUnload
{
    [self setBtCancel:nil];
    [self setTvSMS:nil];
    [self setLbBoxTitle:nil];
    [self setLbSMSTitle:nil];
    [self setLbGap:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void)startRequest
{
    if(!loadingView)
    {
       loadingView = [[RequestLoadingView alloc]
                      initRequestLoadingView:self
                      queueFinishSelector:nil
                      viewFrame:LoadingViewFrame];

    }
    [self getOrderDetail];

    [loadingView addRequestToQueue:req];

    [loadingView startRequestQueue];
    
}
-(void) getOrderDetail{
    NSURL *url=[NSURL URLWithString:url_orderDetail];
    req=[ASIFormDataRequest requestWithURL:url];
    int memberId=[[Config Instance] getMemberId];
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    [req setPostValue:sid forKey:@"member.memberID"];
    [req setPostValue:[[Config Instance]getPassword] forKey:@"member.password"];
    [req setPostValue:[NSString stringWithFormat:@"%d",orderType] forKey:@"orderType"];
    [req setPostValue:orderNoId forKey:@"orderNO"];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate:self];
    
    if (!loadingView.bFirstRequest) {
        [req startAsynchronous];
    }
    
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishReq:(ASIHTTPRequest *)request
{
    isReqFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
//    NSLog(@"%@",dic);
    if([@"SUCCESS" isEqualToString:[dic valueForKey:@"status"]]){
      NSDictionary *data = [dic valueForKey:@"data"];
 //       orderNo.text=orderNoId;
        merchantName.text=[data valueForKey:@"merchantName"];
        bookTime.text=[NSString stringWithFormat:@"%@  %@:%@",[[data valueForKey:@"diningDate"] substringToIndex:10],[data valueForKey:@"diningHour"],[data valueForKey:@"diningMin"]];
     //   foodTime.text=[NSString stringWithFormat:@"%@:%@",[data valueForKey:@"diningHour"],[data valueForKey:@"diningMin"]];//[data valueForKey:@"diningTime"];
        int nums=[[data valueForKey:@"diningNumber"]intValue];
        num.text=[NSString stringWithFormat:@"%d",nums];
        NSString *strconfMes=[data objectForKey:@"orderMemo"];
        if((NSNull *)strconfMes == [NSNull null]){
            _tvSMS.text=@"";
        }else{
            NSString *str=[data valueForKey:@"orderMemo"];
            _tvSMS.text = str;
        }
        _tvSMS.editable=NO;
        NSString *strboxName=[data objectForKey:@"boxNames"];
        if((NSNull *)strboxName == [NSNull null]){
            boxName.text=@"";
        }else{
           boxName.text=[data valueForKey:@"boxNames"];
        }
        NSString *strotherReq=[data objectForKey:@"diningMemo"];
        if((NSNull *)strotherReq == [NSNull null]){
            otherReq.text=@"无";
        }else{
           otherReq.text=[data valueForKey:@"diningMemo"];
        }
//        if([[data objectForKey:@"status"]intValue]==0){
//            _btCancel.hidden=false;
//        }
        if([[data objectForKey:@"status"]intValue]==1
           ||[[data objectForKey:@"status"]intValue]==0){
            NSDate *curDate = [NSDate date];//获取当前日期
//            int cur = [[curDate dateStringWithFormat:@"yyyyMMdd"]intValue];
            NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
            [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *strDining = [NSString stringWithFormat:@"%@ %@:%@:00" ,[[data valueForKey:@"diningDate"] substringToIndex:10] ,[data valueForKey:@"diningHour"],[[data valueForKey:@"diningMin"] intValue]==0?@"00" :[data valueForKey:@"diningMin"]];
            NSDate *date=[formater dateFromString:strDining];
            if ([curDate compare:date]==NSOrderedAscending) {
                _btCancel.hidden=false;
            }
//            NSLog(@"%@",date);
            

        }
        //bookTime.text=[data valueForKey:@"diningDate"];
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"获取订单信息失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isReqFinished = true;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)goBack:(id)sender {
    if (!isReqFinished){
        [req clearDelegatesAndCancel];
        [req cancel];
    }
     [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showMerchant:(id)sender {
    RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
    //传递商户id参数
    view.merchantId = merchantId;
    view.merchantType= orderType;
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];

}
- (IBAction)doCancel:(id)sender {
    NSURL *url=[NSURL URLWithString:url_orderCancel];
    req=[ASIFormDataRequest requestWithURL:url];
    int memberId=[[Config Instance] getMemberId];
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    [req setPostValue:sid forKey:@"member.memberID"];
    [req setPostValue:[[Config Instance]getPassword] forKey:@"member.password"];
    [req setPostValue:orderNoId forKey:@"orderNO"];
    [req setPostValue:[NSString stringWithFormat:@"%d",orderType] forKey:@"orderType"];

    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishCancel:)];
    isReqFinished = false;
    [req setDelegate:self];
    [req startAsynchronous];
}

//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishCancel:(ASIHTTPRequest *)request
{
    isReqFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
   // NSLog(@"%@",dic);
    if(![[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[dic valueForKey:@"log"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        return;

    }else{
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"取消订单成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        if (!isReqFinished){
            [req clearDelegatesAndCancel];
            [req cancel];
        }
        [self.navigationController popViewControllerAnimated:YES];

    }
        
}
@end
